import json

from flask import Flask, request, make_response

from logicclass import Logic

app = Flask(__name__)
logic = Logic()


def maresp(obj):
    resp = make_response(json.dumps(obj))
    resp.headers["Access-Control-Allow-Origin"] = "*"
    resp.headers["Access-Control-Allow-Methods"] = "GET,POST"
    resp.headers["Access-Control-Allow-Headers"] = "x-requested-with,content-type"
    return resp


@app.route("/demolition", methods=["POST"])
def demolition():
    try:
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))

        acvs_id = json_data.get("acvs_id")
        face_id = json_data.get("face_id")

        if not isinstance(acvs_id, str):
            raise Exception

        if (face_id is not None) and (not isinstance(face_id, str)):
            raise Exception
    except Exception:
        return maresp({"msg": "Parameter error", "rtn": -3})
    try:
        # 拆档
        if face_id is None:
            logic.demolition_a(acvs_id)

        # 拆脸
        if face_id is not None:
            logic.demolition_f(acvs_id, face_id)
    except Exception as e:
        return maresp({"msg": str(e), "rtn": -3})
    return maresp({"msg": "OK", "rtn": 0})


@app.route("/merge", methods=["POST"])
def merge():
    try:
        data = request.get_data()
        json_data = json.loads(data.decode("utf-8"))

        acvs_id = json_data.get("acvs_id")
        acvs_p_id = json_data.get("acvs_p_id")
        face_id = json_data.get("face_id")

        if not isinstance(acvs_id, str):
            raise Exception

        if (acvs_p_id is not None) and (face_id is not None):
            raise Exception

        if (acvs_p_id is not None) and (not isinstance(acvs_p_id, str)):
            raise Exception

        if (face_id is not None) and (not isinstance(face_id, str)):
            raise Exception

    except Exception:
        return maresp({"msg": "Parameter error", "rtn": -3})
    try:
        # 拆档
        if face_id is None:
            logic.merge_a(acvs_id, acvs_p_id)

        # 拆脸
        if face_id is not None:
            logic.merge_f(acvs_id, face_id)
    except Exception as e:
        return maresp({"msg": str(e), "rtn": -3})
    return maresp({"msg": "OK", "rtn": 0})


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5100, debug=False)
